<template>
  <view class="bg-[var(--page-bg-color)] min-h-[100vh] pb-[60rpx]" :style="themeColor()" v-if="getMember()">
    <template v-if="!loading">
      <view class="w-full bg-[var(--page-bg-color)]">
        <view class="pb-[210rpx] relative" :style="headerStyle">
          <!-- #ifdef MP-WEIXIN -->
          <top-tabbar :data="param" :scrollBool="topTabarObj.getScrollBool()" class="top-header" />
          <!-- #endif -->
          <view class="text-[70rpx] leading-[90rpx] text-[#fff] pl-[60rpx] font-500 pt-[77rpx] price-font"
            v-if="state.unitType == 0">
            {{ info?.weight || 0 }} </view>
          <view class="text-[70rpx] leading-[90rpx] text-[#fff] pl-[60rpx] font-500 pt-[77rpx] price-font"
            v-if="state.unitType == 1">
            {{ info?.weight * 2 || 0 }} </view>
          <view class="flex items-center pl-[60rpx]">
            <!-- <image class="h-[36rpx] w-[36rpx] -mb-[4rpx]" :src="img('static/resource/images/member/point/icon.png')"
              mode="heightFix" /> -->
            <view class="text-[32rpx] leading-[36rpx] text-[#fff] ml-[10rpx]">初始体重({{ state.unit }})</view>
          </view>
          <view class="side-tab" :style="{ top: topStyle }" @click="toLink('/addon/weight/pages/record')">
            <text class="nc-iconfont nc-icon-jifenduihuanV6xx1 icon"></text>
            <text class="desc">体重记录</text>
          </view>
          <view class="side-tab" :style="{ top: topStyle1 }" @click="handleSetUnitType()">
            <!-- <text class="nc-iconfont nc-icon-jifenduihuanV6xx1 icon"></text> -->
            <text class="desc">{{ state.unitType == 0 ? '斤' : 'KG' }}</text>
          </view>
        </view>
        <view class="sidebar-margin flex flex-col mt-[-178rpx] relative">
          <view
            class="w-[322rpx] h-[80rpx] text-[32rpx] text-[#333] font-500 box-border pl-[30rpx] pt-[var(--pad-top-m)] rounded-tl-[var(--rounded-big)] overflow-hidden mb-[-2rpx]"
            :style="{ backgroundImage: 'url(' + img('static/resource/images/member/point/top_bg.png') + ') ', backgroundSize: '100% 100%', backgroundRepeat: 'no-repeat' }">
            <text class="leading-[42rpx]">目标管理</text>
            <text class="nc-iconfont nc-icon-shezhiV6xx1 text-[32rpx] ml-[10rpx]" @click="() => {
              state.isShowSetTarget = true
            }"></text>
          </view>
          <view
            class="flex items-center px-[30rpx] rounded-[var(--rounded-big)] !rounded-tl-none bg-[#fff] h-[173rpx] box-border">
            <view class="w-[196rpx] flex-shrink-0 text-center">
              <view class="text-[#333] text-[42rpx] leading-[54rpx] price-font" v-if="state.unitType == 0">{{
                info?.targetWeight || 0 }} </view>
              <view class="text-[#333] text-[42rpx] leading-[54rpx] price-font" v-if="state.unitType == 1">{{
                info?.targetWeight * 2 || 0 }} </view>
              <view class="mt-[8rpx] text-[var(--text-color-light6)] text-[32rpx] leading-[36rpx] font-400">
                目标体重({{ state.unit }})
              </view>
            </view>
            <view class="w-[1rpx] h-[50rpx] flex-shrink-0 bg-[var(--temp-bg)] mx-[10rpx]"></view>
            <view class="w-[196rpx] flex-shrink-0 text-center">
              <view class="text-[#333] text-[42rpx] leading-[54rpx] price-font">{{ info?.targetDays || 0 }} </view>
              <view class="mt-[8rpx] text-[var(--text-color-light6)] text-[32rpx] leading-[36rpx] font-400">目标天数</view>
            </view>
            <view class="w-[1rpx] h-[50rpx] flex-shrink-0 bg-[var(--temp-bg)] mx-[10rpx]"></view>
            <view class="w-[196rpx] min-w-[209.33rpx] flex-shrink-0 text-center">
              <view class="text-[#333] text-[42rpx] leading-[54rpx] price-font">{{ info?.reachRate || 0 }} </view>
              <view class="mt-[8rpx] text-[var(--text-color-light6)] text-[32rpx] leading-[36rpx] font-400">达成率(%)
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="mt-[var(--top-m)] mb-[var(--top-m)] sidebar-margin card-template">
        <view class="title !text-[32rpx] flex justify-between">
          <view>美好尽在每日上称</view>
          <view>
            <!-- <text class="leading-[42rpx]">修改</text> -->
            <text class="nc-iconfont nc-icon-shezhiV6xx1 text-[32rpx] ml-[10rpx]" @click="() => {
              state.isShowSetWeightValue = true
            }"></text>
          </view>

        </view>
        <view class="mt-[60rpx]">
          <view class="charts-box">
            <!-- #ifdef H5 -->
            <qiun-data-charts type="gauge" :opts="opts" :chartData="chartData" />
            <!-- #endif -->
            <!-- #ifdef MP-WEIXIN || APP-PLUS -->
            <qiun-data-charts type="gauge" :opts="opts" :chartData="chartData" :canvas2d="true"
              canvasId="SvDlYfwZrEDMKVyotHGsDUpFQbHDBaIp" />
            <!-- #endif -->

          </view>
          <button class="rounded-[40rpx] flex-center !bg-transparent text-[32rpx] font-500"
            :style="{ width: '490rpx', height: '80rpx', border: 'none', color: '#fff', backgroundImage: `url(${img('static/resource/images/app/button_bg2.png')})`, backgroundSize: '100%', backgroundRepeat: 'no-repeat' }"
            shape="circle" @click="weigh">
            <text>立即上称</text>
          </button>

        </view>
      </view>

    </template>
    <!-- 设置目标 -->
    <view @touchmove.prevent.stop>
      <u-popup class="weight-popup" :closeable="true" :show="state.isShowSetTarget"
        @close="state.isShowSetTarget = false" zIndex="999999">
        <view class="min-h-[480rpx] popup-common" @touchmove.prevent.stop>
          <view class="title !pb-[30rpx]">设置目标</view>
          <scroll-view class="h-[70vh]" scroll-y="true">
            <view class="px-[var(--popup-sidebar-m)] pt-[30rpx]">
              <u-form labelPosition="left" :model="state.model" :rules="rules" labelWidth="200rpx"
                :labelStyle="{ 'font-size': '32rpx' }" ref="formRef">
                <view class="mt-[10rpx]">
                  <u-form-item :label="`目前体重(${state.unitType == 0 ? 'KG' : '斤'})`" prop="weight">
                    <u-input fontSize="32rpx" v-model.trim="state.model.weight" border="none"
                      placeholder-class="!text-[var(--text-color-light9)] text-[32rpx]" clearable
                      placeholder="请设置当前体重"></u-input>
                  </u-form-item>
                </view>
                <view class="mt-[10rpx]">
                  <u-form-item :label="`目标体重(${state.unitType == 0 ? 'KG' : '斤'})`" prop="targetWeight">
                    <u-input fontSize="32rpx" v-model.trim="state.model.targetWeight" border="none"
                      placeholder-class="!text-[var(--text-color-light9)] text-[32rpx]" clearable
                      placeholder="请设置目标体重"></u-input>
                  </u-form-item>
                </view>
                <view class="mt-[10rpx]">
                  <u-form-item label="目标天数(天)" prop="targetDays">
                    <u-input fontSize="32rpx" v-model.trim="state.model.targetDays" border="none"
                      placeholder-class="!text-[var(--text-color-light9)] text-[32rpx]" clearable
                      placeholder="请设置目标天数"></u-input>
                  </u-form-item>
                </view>
              </u-form>
            </view>
          </scroll-view>
          <view class="btn-wrap">
            <button class="primary-btn-bg btn" @click="onSubmitTarget">确定</button>
          </view>
        </view>
      </u-popup>

    </view>
    <!-- 设置体重 -->
    <view @touchmove.prevent.stop>
      <u-popup class="weight-popup" :closeable="true" :show="state.isShowSetWeightValue"
        @close="state.isShowSetWeightValue = false" zIndex="999999">
        <view class="min-h-[480rpx] popup-common" @touchmove.prevent.stop>
          <view class="title !pb-[30rpx]">设置体重</view>
          <scroll-view class="h-[70vh]" scroll-y="true">
            <view class="px-[var(--popup-sidebar-m)] pt-[30rpx]">
              <u-form labelPosition="left" :model="state.model" :rules="rules" labelWidth="200rpx"
                :labelStyle="{ 'font-size': '32rpx' }" ref="formRef">
                <view class="mt-[10rpx]">
                  <u-form-item :label="`当前体重(${state.unitType == 0 ? 'KG' : '斤'})`" prop="weight">
                    <u-input fontSize="32rpx" v-model.trim="state.model.weight" border="none"
                      placeholder-class="!text-[var(--text-color-light9)] text-[32rpx]" clearable
                      placeholder="请设置当前体重"></u-input>
                  </u-form-item>
                </view>

              </u-form>
            </view>
          </scroll-view>
          <view class="btn-wrap">
            <button class="primary-btn-bg btn" @click="onSubmitWeightvalue">确定</button>
          </view>
        </view>
      </u-popup>

    </view>
    <view @touchmove.prevent.stop class="weight-img-popup">
      <u-popup class="weight-img-popup" :show="state.isWeight" border-radius="30" mode="center"
        :safe-area-inset-bottom="false" :closeable="true" @close="state.isWeight = false" zIndex="999999">
        <view class=" flex" @touchmove.prevent.stop>

          <image style="width: 350rpx; height:350rpx;"
            src="https://files.meton.vip/b48649d6ee6a80e5f345eea2aff61c1ca4f0510400b01ae583c899eaf3d69ecf.png">
          </image>
        </view>
      </u-popup>
    </view>

    <loading-page :loading="loading"></loading-page>
  </view>
  <!-- 水印 -->
  <watermark></watermark>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { onLoad, onReady, onShow } from '@dcloudio/uni-app'
import { t } from '@/locale'
import { redirect, img, pxToRpx, getMember } from '@/utils/common';
import { WeightScale as useWeightScale, setBodyFlat } from '@/app/api/member';
import { topTabar } from '@/utils/topTabbar'
import useMemberStore from '@/stores/member';
import { getUser } from '@/app/api/shopMember';


/********* 自定义头部 - start ***********/
const topTabarObj = topTabar()
let param = topTabarObj.setTopTabbarParam({ title: '体重管理' })
/********* 自定义头部 - end ***********/

// 获取系统状态栏的高度
let menuButtonInfo: any = {};
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif
const headerStyle = computed(() => {
  return {
    backgroundImage: 'url(' + img('static/resource/images/member/point/point_bg.png') + ') ',
    backgroundSize: 'cover',
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'bottom',
    // paddingTop:Object.keys(menuButtonInfo).length?(Number(menuButtonInfo.height) * 2 + menuButtonInfo.top * 2 + 77)+'rpx':'77rpx',
  }
})
const topStyle = computed(() => {
  let style = Object.keys(menuButtonInfo).length ? (pxToRpx(Number(menuButtonInfo.height)) + pxToRpx(menuButtonInfo.top) + 50) + 'rpx;' : '50rpx'
  return style
})
const topStyle1 = computed(() => {
  let style = Object.keys(menuButtonInfo).length ? (pxToRpx(Number(menuButtonInfo.height)) + pxToRpx(menuButtonInfo.top) + 120) + 'rpx;' : '120rpx'
  return style
})
const memberStore = useMemberStore()
const chartData = ref({
  categories: [
    { value: 0.2, color: '#1890ff' },
    { value: 0.8, color: '#2fc25b' },
    { value: 1, color: '#f04864' }
  ],
  series: [
    {
      name: "完成率",
      data: 0
    }
  ]
})
const opts = ref({
  color: ["#ff4500", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
  padding: undefined,
  title: {
    name: "0",
    fontSize: 25,
    color: "#333",
    offsetY: 0
  },
  subtitle: {
    name: "KG",
    fontSize: 15,
    color: "#333",
    offsetY: 0
  },
  extra: {
    gauge: {
      type: "progress",
      width: 20,
      labelColor: "#666666",
      startAngle: 0.75,
      endAngle: 0.25,
      startNumber: 0,
      endNumber: 100,
      labelFormat: "",
      splitLine: {
        fixRadius: -10,
        splitNumber: 10,
        width: 15,
        color: "#FFFFFF",
        childNumber: 5,
        childWidth: 12
      },
      pointer: {
        width: 24,
        color: "auto"
      }
    }
  }
})
//  #ifdef MP-WEIXIN
opts.value.extra = {
  gauge: {
    type: "progress",
    width: 50,
    labelColor: "#666666",
    startAngle: 0.75,
    endAngle: 0.25,
    startNumber: 0,
    endNumber: 100,
    labelFormat: "",
    splitLine: {
      fixRadius: -10,
      splitNumber: 10,
      width: 15,
      color: "#FFFFFF",
      childNumber: 5,
      childWidth: 12
    },
    pointer: {
      width: 24,
      color: "auto"
    }
  }
}
// #endif

//称重
const formRef = ref()
const state = reactive({
  bluetooth: {},
  isWeight: false, //是否称重
  weightValue: 0 as any,
  resistorValue: 0 as any,
  unit: 'KG' as any,
  unitType: 0,   //0:kg 1:斤
  currentTab: 0,
  currentRecordTab: 0,
  isShowSetTarget: false,
  isShowSetWeightValue: false,
  model: {
    weight: '',
    targetDays: '',
    targetWeight: '',
  },
});
const handleSetUnitType = () => {
  // 如果单位类型是KG 则切换到斤
  if (state.unitType == 0) {
    state.unitType = 1;
    state.unit = '斤';
    opts.value.title.name = (state.weightValue * 2).toString();
    opts.value.subtitle.name = '斤'
    uni.setStorageSync('weightUnitType', state.unitType)

    return
  }
  // 如果单位类型是斤 则切换到KG
  if (state.unitType == 1) {
    state.unitType = 0;
    state.unit = 'KG';
    opts.value.title.name = state.weightValue;
    opts.value.subtitle.name = 'KG'
    uni.setStorageSync('weightUnitType', state.unitType)

    return
  }


}

const rules = computed(() => {
  return {

    'weight': {
      type: 'string',
      required: true,
      message: '请输入当前体重',
      trigger: ['blur', 'change'],
    },
    'targetDays': {
      type: 'string',
      required: true,
      message: '请输入目标天数',
      trigger: ['blur', 'change'],
    },
    'targetWeight': {
      type: 'string',
      required: true,
      message: '请输入目标体重',
      trigger: ['blur', 'change'],
    }
  }
})

const ab2hex = (buffer: any[]) => {
  const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
    return ('00' + bit.toString(16)).slice(-2);
  });
  return hexArr.join('');
};
const getStringBytes = (str: string) => {
  let len = 0;
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i);
    if (code <= 0x7f) {
      len += 1;
    } else if (code <= 0x7ff) {
      len += 2;
    } else if (code >= 0xd800 && code <= 0xdfff) {
      // surrogate pair
      len += 4;
      i++; // 跳过配对的代理项
    } else {
      len += 3;
    }
  }
  return len;
};
const getBit = (num: any, n: number) => {
  return (num >> n) & 1;
};
const setPrecision = (precision: string) => {
  console.log(precision);
  if (precision == '00') {
    return 1;
  }
  if (precision == '01') {
    return 0;
  }
  if (precision == '10') {
    return 2;
  }
};
const setUnit = (precision: string) => {
  if (precision == '00') {
    return 'KG';
  }
  if (precision == '01') {
    return '斤';
  }
};
const splitFromPenultimateChar = (str: string, precision: number) => {
  if (precision == 0) {
    return str;
  }
  if (str.length > precision) {
    return str.slice(0, -precision) + '.' + str.slice(-precision);
  }
  return str; // 如果字符串长度为1，则返回原字符串和空字符串
};
const parseBroadcastData = (broadcastData: string | any[]) => {
  let weightBytes = broadcastData[4] + broadcastData[5] + broadcastData[6] + broadcastData[7]; //体重字节
  let resistorBytes =
    broadcastData[8] + broadcastData[9] + broadcastData[10] + broadcastData[11]; //电阻字节
  let msgBytes = broadcastData[16] + broadcastData[17];
  let weightData = parseInt(weightBytes, 16);
  let resistorData = parseInt(resistorBytes, 16);
  let msgData = parseInt(msgBytes, 16).toString(2);
  let isLock = getBit(msgData, 0); //0非锁定数据 1锁定数据
  let precision = setPrecision(getBit(msgData, 2) + '' + getBit(msgData, 1)); //00 1位小数 01 0位小数 10 2位小数
  let unit = setUnit(getBit(msgData, 4) + '' + getBit(msgData, 3)); //00 KG(默认) 01 斤 10 LB 11ST:LB
  countWeight(weightData, isLock, precision, unit, resistorData);
};
const onSubmitTarget = () => {


  formRef.value.validate().then(async () => {
    state.isShowSetTarget = false;

    if (state.unitType == 1) {
      state.model.weight = Number(state.model.weight) / 2
      state.model.targetWeight = Number(state.model.targetWeight) / 2

    }
    await setBodyFlat(state.model);
    uni.showToast({
      title: '设置成功',
      icon: "none"
    })
    getMemberInfo()
  })

};
/**
 * 提交体重值
 * 1. 根据单位类型转换重量值（斤转KG）
 * 2. 调用称重接口保存数据
 * 3. 刷新会员信息并显示成功提示
 */
const onSubmitWeightvalue = async () => {
  state.isShowSetWeightValue = false;
  let weightValue = state.model.weight
  // 如果是斤 转成KG
  if (state.unitType == 1) {
    weightValue = Number(state.model.weight) / 2
  }


  let params = {
    weight: weightValue,

  };
  await useWeightScale(params);
  uni.hideLoading()

  getMemberInfo()
  uni.showToast({
    title: '设置成功',
    icon: "none"
  })
}

const WeightScale = async (unit: any) => {
  // 如果是斤 转为KG
  let weight = state.weightValue;
  if (unit == '斤') {
    weight = Number(state.weightValue) / 2
  }

  let params = {
    weight: weight,
    impedance: state.resistorValue, //电阻
  };
  uni.showLoading({
    title: '计算中',
  })
  await useWeightScale(params);
  uni.hideLoading()
  getMemberInfo()

};
const stopBluetooth = () => {
  uni.stopBluetoothDevicesDiscovery({
    success(res) {
    },
  });
};
const countWeight = (weightData: number, isLock: number, precision: number | undefined, unit: string | undefined, resistorData: number) => {
  let weightStr = weightData.toString();
  let resistorDataStr = resistorData.toString();
  if (isLock) {
    state.isWeight = false;
    stopBluetooth();
    state.weightValue = splitFromPenultimateChar(weightStr, precision);
    state.resistorValue = splitFromPenultimateChar(resistorDataStr, precision);
    // state.unit = unit;
    // 如果体重秤是斤 
    if (unit == '斤') {
      if (state.unitType == 0) {
        // 展示的单位是公斤
        opts.value.title.name = state.weightValue / 2;

      }
      if (state.unitType == 1) {
        opts.value.title.name = state.weightValue;

      }

    }
    // 如果体重秤是KG
    if (unit == 'KG') {
      if (state.unitType == 0) {
        // 展示的单位是公斤
        opts.value.title.name = state.weightValue;

      }
      if (state.unitType == 1) {
        opts.value.title.name = state.weightValue * 2;

      }

    }
    // opts.value.subtitle.name = unit || 'KG'
    chartData.value.series = [
      {
        name: '完成率',
        data: Number(state.weightValue) / 200,
      },
    ];
    WeightScale(unit);
  }
}; //计算体重

const weigh = () => {
  const innerAudioContext = uni.createInnerAudioContext();
  innerAudioContext.autoplay = true;
  innerAudioContext.src =
    'https://files.meton.vip/ed5db168f8e69f18f27037bcffacdfc04be6e5fc2f0eefdd87420c83e0b0063b.mp3';
  innerAudioContext.onPlay(() => {
    console.log('开始播放');
  });
  uni.openBluetoothAdapter({
    success(res) {
      console.log('蓝牙打开');

      state.isWeight = true;

      uni.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success(res) {
          console.log('开始搜索设备');

          uni.onBluetoothDeviceFound((res) => {
            let broadcastData = ab2hex(res.devices[0].advertisData);
            let broadcastStringBytes = getStringBytes(broadcastData);
            if (broadcastStringBytes == 30 && broadcastData.startsWith('c0')) {
              console.log(broadcastData);

              parseBroadcastData(broadcastData);
            }
          });
        },
        fail(e) {
          state.isWeight = false;
          console.log(e);
        },
      });
    },
    fail(e) {
      state.isWeight = false;
      console.log(e);
    },
  });
}
// const info = computed(async () => {
//   // 装修模式
//   let userId = ''
//   if (uni.getStorageSync('wapShopMember')) {
//     userId = uni.getStorageSync('wapShopMember').id;
//   }
//   const { data: memberInfo } = await getUser(userId)

//   return memberInfo;
// })
const info = ref()
const getMemberInfo = async () => {
  let userId = ''
  if (uni.getStorageSync('wapShopMember')) {
    userId = uni.getStorageSync('wapShopMember').id;
    const { data: memberInfo } = await getUser(userId)
    info.value = memberInfo
    setTimeout(() => {
      state.weightValue = info.value?.currentWeight || 0
      if (state.weightValue) {
        if (state.unitType == 0) {
          opts.value.title.name = info.value?.currentWeight || 0

        }
        if (state.unitType == 1) {
          opts.value.title.name = info.value?.currentWeight * 2 || 0

        }
        chartData.value.series = [
          {
            name: '完成率',
            data: Number(state.weightValue) / 200,
          },
        ];
      }
    }, 0)
  }

}




//减掉的体重
const minusWeight = computed(() => {
  if (info.value?.targetWeight && info.value?.weight) {
    let weight = info.value.targetWeight - info.value.weight;
    return weight > 0 ? weight.toFixed(2) : 0;
  } else {
    return 0
  }

});
//积分任务
const pointList = ref([]);
const loading = ref(true)
onLoad(async () => {

  loading.value = false
})
onReady(() => {

})
onShow(async () => {
  state.unitType = uni.getStorageSync('weightUnitType')
  if (state.unitType == 0) {
    state.unit = 'KG';
    opts.value.subtitle.name = 'KG'
  }
  if (state.unitType == 1) {
    state.unit = '斤';
    opts.value.subtitle.name = '斤'
  }
  await getMemberInfo()


})
const toLink = (url = '', param = {}) => {
  redirect({ url, param })
}
</script>

<style lang="scss" scoped>
.bg-color {
  background-color: rgba(102, 102, 102, 0.4);
}

.charts-box {
  width: 100%;
  height: 500rpx;
  z-index: 1 !important;
}

::v-deep .weight-popup .u-slide-up-enter-to {
  z-index: 999999 !important;
}

::v-deep .weight-img-popup .u-popup__content {
  background-color: transparent !important;
}

.weight-img-popup {

  :deep(.u-transition),
  :deep(.u-popup__content) {
    background-color: transparent;
  }
}
</style>
